#!/bin/bash

function start_workbase {
	echo "Checking if oplog has been enabled, and enabling if not"
	LC_ALL=C mongo $SNAP/bin/initreplset.js
	
	export DEPLOY_METHOD=snap
	export NODE_ENV=production
	export BABEL_CACHE_DIR=/tmp
	export ROOT_URL=http://localhost
  export PORT="$(snapctl get port)"
  export MONGO_URL="$(snapctl get mongo-url)"
  export MONGO_OPLOG_URL="$(snapctl get mongo-oplog-url)"
  export UPLOADS_DIR=$SNAP_COMMON/uploads
	siteurl="$(snapctl get siteurl)"
  if [ -n "$siteurl" ]; then
	  export OVERWRITE_SETTING_Site_Url=$siteurl
	fi

	for filename in $SNAP_COMMON/*.env; do
    while read env_var; do
	    export "$env_var"
    done < $filename
	done

	node $SNAP/main.js
}

sleep_time=5
try_times=0

function try_start {

	search=$(ps --pid $(cat $SNAP_COMMON/mongod.pid) -o comm=)

	if [ $search ]
  	then
      start_workbase
  	else
		if [[ "$try_times" == 5 || "$try_times" > 5 ]]; then
      echo "Was unable to connect to Mongo.  Please make sure Mongo has started successfully: sudo systemctl status snap.workbase-server.workbase-mongo to view logs: sudo journalctl -u snap.workbase-server.workbase-mongo"
 			exit 1;
		fi

		((try_times += 1))
		((sleep_time += 5))
  	echo "Mongo is not available, can't start. Waiting ${sleep_time} seconds and trying again"
		sleep $sleep_time
		try_start
	fi
}

try_start
